package org.wangp.gateway.oa.config;

import cn.hutool.core.map.MapUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import org.wangp.gateway.oa.domain.UserDetail;

import java.security.KeyPair;

/**
 * @author wangpeng (๑•ᴗ•๑)
 * @since 2021/10/6 2:53
 */
@Configuration
public class TokenConfig {

	@Bean
	public TokenEnhancer tokenEnhancer() {
		return (accessToken, authentication) -> {
			final var userDetail = (UserDetail) authentication.getPrincipal();
			((DefaultOAuth2AccessToken) accessToken)
					.setAdditionalInformation(MapUtil.<String, Object>builder().put("id", userDetail.getId()).map());
			return accessToken;
		};
	}

	@Bean
	public JwtAccessTokenConverter accessTokenConverter(final KeyPair keyPair) {
		final JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
		jwtAccessTokenConverter.setKeyPair(keyPair);
		return jwtAccessTokenConverter;
	}

	@Bean
	public KeyPair keyPair() {
		return new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray()).getKeyPair("jwt",
				"123456".toCharArray());
	}
}
